package com.zwj.design.test.behavior.strategy.observer;

import java.util.Observable;
import java.util.Observer;

/**
 * 观察者
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/3/18 23:44
 */
public class User implements Observer {
    private Long productId;
    private Long price;
    /**
     * 被观察者
     */
    private Observable observable;

    /**
     * 将当前用户注册为观察者
     *
     * @param observable 被观察者
     */
    public User(Observable observable) {
        this.observable = observable;
        observable.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof Product) {
            Product product = (Product) o;
            this.productId = product.getId();
            this.price = product.getPrice();
            displayPrice();
        }
    }

    /**
     * 用户查看订阅商品价格
     */
    public void displayPrice() {
        System.err.println("价格发生了变化，当前商品ID为：" + this.productId + "价格为：" + this.price + "元");
    }
}
